package visitor.outputvisitor

import database.DB
import database.DataBaseImpl
import dsl.TableSchema
import org.junit.jupiter.api.Test
import util.toSqlString
import java.sql.Connection

internal class SqlserverOutPutVisitorTest {

    @Test
    fun visitSqlUpsert() {
        val dataBaseImpl = object : DataBaseImpl() {
            override val db: DB = DB.SQLSERVER
            override val isTransaction: Boolean
                get() = false

            override fun getConnection(): Connection {
                throw Exception("Not have Connection")
            }
        }
        val upsert = dataBaseImpl.toUpsert(Settings("ADD_BOX_CODE", "aaaaaa"))
        println("upsert sql = ${toSqlString(upsert, dataBaseImpl.db)}")

        // 该表定义为：
        // create table settings
        // (
        //    [key]   varchar(20) not null
        //        constraint settings_pk
        //            primary key nonclustered,
        //    content varchar(20) not null
        // )

        // 原上方语句输出:
        // upsert sql = MERGE INTO "settings" "t1" USING (SELECT 'aaaaaa' AS "content", 'ADD_BOX_CODE' AS "key") "t2"
        // ON ("t1"."key" = "t2"."key")
        // WHEN MATCHED THEN UPDATE SET "t1"."content" = "t2"."content"
        // WHEN NOT MATCHED THEN INSERT ("t1"."content", "t1"."key") VALUES ('aaaaaa', 'ADD_BOX_CODE')

        // 对于 SQL Server 2016 存在标识符问题，且尾部缺少语句结束符，执行结果：
        // 行 4: MERGE 语句中使用的插入列列表中不能包含多部分标识符。请改用单部分标识符。

        // 现上方输出：
        // upsert sql = MERGE INTO "settings" "t1" USING (SELECT 'aaaaaa' AS "content", 'ADD_BOX_CODE' AS "key") "t2"
        // ON ("t1"."key" = "t2"."key")
        // WHEN MATCHED THEN UPDATE SET "t1"."content" = "t2"."content"
        // WHEN NOT MATCHED THEN INSERT ("content", "key") VALUES ('aaaaaa', 'ADD_BOX_CODE');


    }

}

data class Settings(
    var key: String? = null,
    var content: String? = null
) {
    companion object Table : TableSchema("settings") {
        @JvmField
        val key = column("key").primaryKey()

        @JvmField
        val content = column("content")
    }
}